package io.renren.modules.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisUtils;
import io.renren.entity.CommonContentEntity;
import io.renren.modules.business.service.CommonContentService;
import io.renren.modules.business.vo.CommonContentVO;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.shiro.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Slf4j
@RequestMapping("business/commoncontent")
public class CommonContentController {

    @Autowired
    private CommonContentService commonContentService;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    SysUserDao sysUserDao;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = commonContentService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        CommonContentEntity commonContentEntity = commonContentService.getById(id);
        return R.ok().put("commonContent", commonContentEntity);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CommonContentVO contentVO) {
        try {
            CommonContentEntity commonContentEntity = new CommonContentEntity();
            commonContentEntity.setContentKey(contentVO.getContentKey());
            commonContentEntity.setContentOne(contentVO.getContentOne());
            commonContentEntity.setContentThree(contentVO.getContentThree());
            commonContentEntity.setContentTwo(contentVO.getContentTwo());
            commonContentEntity.setCreateTime(new Date());
            Long userId = ShiroUtils.getUserId();
            QueryWrapper wrapper = new QueryWrapper<SysUserEntity>();
            wrapper.eq("user_id", userId);
            SysUserEntity userEntity = sysUserDao.selectOne(wrapper);
            commonContentEntity.setCreator(userEntity.getUsername());
            commonContentEntity.setDes(contentVO.getDes());
            commonContentEntity.setEnabled(0);
            commonContentEntity.setImageUrls(contentVO.getImageUrls());
            commonContentEntity.setTitle(contentVO.getTitle());
            commonContentEntity.setUpdateTime(commonContentEntity.getCreateTime());
            commonContentEntity.setUpdator(userEntity.getUsername());
            commonContentService.save(commonContentEntity);

            return R.ok();
        } catch (Exception e) {
            log.error("保存内容失败", e);
            return R.error(1, "保存内容失败");
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody CommonContentVO contentVO) {
        try {

            QueryWrapper queryWrapper = new QueryWrapper<CommonContentEntity>();
            queryWrapper.eq("id", contentVO.getId());
            CommonContentEntity commonContentEntity = commonContentService.getOne(queryWrapper);
            if (commonContentEntity == null) {
                return R.error(1, "该内容已经不存在");
            }

            Long userId = ShiroUtils.getUserId();
            QueryWrapper wrapper = new QueryWrapper<SysUserEntity>();
            wrapper.eq("user_id", userId);
            SysUserEntity userEntity = sysUserDao.selectOne(wrapper);
            UpdateWrapper updateWrapper = new UpdateWrapper<CommonContentEntity>();
            updateWrapper.eq("id", contentVO.getId());
            updateWrapper.set("content_key", contentVO.getContentKey());
            updateWrapper.set("image_urls", contentVO.getImageUrls());
            updateWrapper.set("content_one", contentVO.getContentOne());
            updateWrapper.set("content_two", contentVO.getContentTwo());
            updateWrapper.set("content_three", contentVO.getContentThree());
            updateWrapper.set("des", contentVO.getDes());
            updateWrapper.set("title", contentVO.getTitle());
            updateWrapper.set("updator", userEntity.getUsername());
            commonContentService.update(updateWrapper);

            String key = "common_content_" + commonContentEntity.getContentKey();
            redisUtils.delete(key);
            return R.ok();
        } catch (Exception e) {
            log.error("修改内容失败", e);
            return R.error(1, "修改内容失败");
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {

        List<String> allKeys = new ArrayList<>();
        if (ids != null && ids.length > 0) {
            for (Long id : ids) {
                QueryWrapper wrapper = new QueryWrapper<CommonContentEntity>();
                wrapper.eq("id", id);
                CommonContentEntity commonContentEntity = commonContentService.getBaseMapper().selectOne(wrapper);
                if (commonContentEntity != null) {
                    String key = "common_content_" + commonContentEntity.getContentKey();
                    allKeys.add(key);
                }
            }
        }
        commonContentService.removeByIds(Arrays.asList(ids));
        for (String key : allKeys) {
            redisUtils.delete(key);
        }

        return R.ok();
    }

}
